package cn.calm.osgi.admin.bundle.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.log4j.Logger;

public class Dao {
	private static final Logger log=Logger.getLogger(Dao.class);
	private DataSource source;
	public Dao() {
		try {
			Context context=new InitialContext();
			log.info("dataSource jndi:java:comp/env/jdbc/calmdesk");
			source=(DataSource) context.lookup("java:comp/env/jdbc/calmdesk");
		} catch (NamingException e) {
			e.printStackTrace();
		}
	}
	
	public <T> List<T> query(QueryRsultMapping<T> mapping){
		log.debug("query statr");
		List<T> list=new ArrayList<T>();
		Connection con = null;
		try {
			con=source.getConnection();
			log.info("query sql:"+mapping.getSql());
			PreparedStatement stat=con.prepareStatement(mapping.getSql().toLowerCase());
			mapping.setParameter(stat);
			
			ResultSet result= stat.executeQuery();
			while(result.next()){
				list.add(mapping.map(result));
			}
		} catch (SQLException e) {
			log.error(e);
		}finally{
			if(con!=null){
				try {
					con.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		log.debug("query end");
		return list;
	}

	public int update(SqlMapping sqlMapping) {
		log.debug("update statr");
		Connection con = null;
		try {
			con=source.getConnection();
			PreparedStatement stat = null;
			if(sqlMapping.getPrepareSql()!=null){
				log.info("PrepareSql:"+sqlMapping.getPrepareSql().toLowerCase());
				stat=con.prepareStatement(sqlMapping.getPrepareSql());
				stat.executeUpdate();
			}
			log.info("Sql:"+sqlMapping.getSql());
			stat=con.prepareStatement(sqlMapping.getSql().toLowerCase());
			
			sqlMapping.setParameter(stat);
			int i= stat.executeUpdate();
//			con.commit();
			return i;
		} catch (SQLException e) {
			e.printStackTrace();
			log.error(e);
		}finally{
			if(con!=null){
				try {
					con.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			log.debug("update end");
		}
		return 0;
	}
}
